package com.core.sms.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.common.exception.BusinessException;
import com.core.sms.common.AbstractSms;

/**
 * @Author: zql
 * @Description:
 * @Data: 8:51 2021/7/13
 */
public class AliAbstractSms extends AbstractSms {
    com.aliyun.dysmsapi20170525.Client client;

    String smsSignName;

    String smsTemplateCode;

    @Override
    public boolean senCode(String mobile,String code) {
        return senCode(mobile, smsTemplateCode, smsSignName,code);
    }

    public AliAbstractSms(String accessKeyId, String accessKeySecret, String smsSignName, String smsTemplateCode) throws Exception {
        client = createClient(accessKeyId,accessKeySecret);
        this.smsSignName =smsSignName;
        this.smsTemplateCode =smsTemplateCode;
    }

    public com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId,String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public boolean senCode(String mobile,String smsTemplateCode, String smsSignName,String code) throws BusinessException {
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers( mobile);
        request.setSignName(smsSignName);
        request.setTemplateCode(smsTemplateCode);
        JSONObject codeJson = new JSONObject();
        codeJson.put("code", code);
        request.setTemplateParam(codeJson.toJSONString());
        try {
            client.sendSms(request);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
